import axios from "axios";

const instance = axios.create({
  baseURL: process.env.NODE_ENV === "development" ? "/api" : "/",
  timeout: 3000,
});

instance.interceptors.request.use((config) => {
  const token = localStorage.getItem("token");
  if (token) {
    config.headers.Authorization = `${token}`;
  }
  return config;
});

instance.interceptors.response.use(
  (response) => {
    const { data, headers } = response;
    if (headers.authorization) {
      localStorage.setItem("token", headers.authorization);
    }
    return data;
  },
  (error) => {
    const { status } = error;
    if (status === 401) {
      localStorage.removeItem("token");
      location.href = location.protocol + "//" + location.host + "/#/login";
    }
    return Promise.reject(error);
  }
);

export default instance;
